package com.pshcp.doctor.api;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.external.common.WebServiceException;
import com.external.service.WsRequestService;
import com.external.ws.soap.entity.dto.GetSchedulingDTO;
import com.external.ws.soap.entity.dto.OrderRegisterDTO;
import com.external.ws.soap.entity.dto.PatInfoQueryDTO;
import com.external.ws.soap.entity.res.OrderRegisterRes;
import com.external.ws.soap.entity.res.PatInfoRes;
import com.external.ws.soap.entity.res.Scheduling;
import com.framework.base.ResultBuilder;
import com.framework.base.ResultDTO;
import com.framework.exception.BizException;
import com.framework.logaop.Log;
import com.framework.logaop.LogSourceEnum;
import com.framework.logaop.LogTypeEnum;
import com.framework.thread.ReqComTool;
import com.framework.tool.CommonTool;
import com.pshcp.common.enums.RegTypeEnum;
import com.pshcp.doctor.ao.schedule.DoctorScheduleAO;
import com.pshcp.doctor.ao.schedule.DoctorScheduleConfirmAO;
import com.pshcp.doctor.ao.schedule.QueryPatientAO;
import com.pshcp.doctor.tool.DoctorScheduleTool;
import com.pshcp.doctor.vo.schedule.DoctorScheduleVO;
import com.pshcp.doctor.vo.schedule.PatInfoResVO;
import com.pshcp.domain.dto.DoctorScheduleDTO;
import com.pshcp.domain.model.Doctor;
import com.pshcp.domain.model.DoctorSchedule;
import com.pshcp.domain.model.OrderReg;
import com.pshcp.domain.model.Patient;
import com.pshcp.service.DoctorScheduleService;
import com.pshcp.service.DoctorService;
import com.pshcp.service.OrderRegService;
import com.pshcp.service.PatientService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: TODO
 * @Author: xiaoche
 * @Date: 2022/11/6 16:10
 */
@Api(tags = {"医生端-诊前加号接口"})
@Slf4j
@RestController
@RequestMapping("/api/doctor/schedule")
public class DoctorScheduleAPI {

    @Autowired
    private WsRequestService wsRequestService;

    @Autowired
    private DoctorService doctorService;

    @Autowired
    private PatientService patientService;

    @Autowired
    private OrderRegService orderRegService;

    @Autowired
    private DoctorScheduleService doctorScheduleService;


    @Value("${custom.patient.reg-refresh-time:15:00:00}")
    private String regRefreshTime;

    @Value("${custom.patient.reg-limit-day:7}")
    private Integer regLimitDay;

    @Value("#{'${custom.desc.areas}'.split(',')}")
    private List<String> areas;

    @Value("${custom.desc.app-name}")
    private String appName;

    @ApiOperation("医生排班时间")
    @Log(source = LogSourceEnum.PATIENT_APP, type = LogTypeEnum.SELECT, desc = "医生排班时间")
    @PostMapping("/scheduleDay")
    public ResultDTO<List<String>> scheduleDay() {
        List<String> days = new ArrayList<>();
        //下午3点 自动放号
        int limitDay = regLimitDay;
        if (DateUtil.current() >
                DateUtil.parseDateTime(DateUtil.today() + " " + regRefreshTime).getTime()) {
            limitDay++;
        }
        for (int i = 1; i <= limitDay; i++) {
            DateTime dateTime = DateUtil.offsetDay(new Date(), i);
            String temp = dateTime.toDateStr() + " " + dateTime.dayOfWeekEnum().toChinese();
            days.add(temp);
        }
        return ResultBuilder.success(days);
    }

    @ApiOperation("筛选号源")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.SELECT, desc = "筛选号源")
    @PostMapping("/getDoctorScheduleList")
    public ResultDTO<List<DoctorScheduleVO>> getDoctorScheduleList(@RequestBody DoctorScheduleAO doctorScheduleAO) throws WebServiceException {
        if(ObjectUtils.isEmpty(doctorScheduleAO.getSchDate())){
            doctorScheduleAO.setSchDate(DateUtil.today());
            doctorScheduleAO.setSchDay(regLimitDay);
        }
        Doctor doctor = doctorService.findById(ReqComTool.getUserId());
        DoctorScheduleDTO doctorScheduleDTO = DoctorScheduleTool.buildGetDoctorScheduleList(doctor, doctorScheduleAO);
        List<DoctorSchedule> schedulings = doctorScheduleService.list(doctorScheduleDTO);
        List<DoctorScheduleVO> list = CommonTool.copyPropertiesList(schedulings, DoctorScheduleVO.class);
        DoctorScheduleTool.buildArea2ScheduleVO(list, areas, doctor);
        return ResultBuilder.success(list);
    }

    @ApiOperation("选择患者(根据患者卡搜索)")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.SELECT, desc = "选择患者(根据患者卡搜索)")
    @PostMapping("/queryPatient")
    public ResultDTO<PatInfoResVO> queryPatient(@RequestBody QueryPatientAO QueryPatientAO) throws BizException {
        PatInfoQueryDTO patInfoQueryDTO = DoctorScheduleTool.buildPatInfoQueryDTO(QueryPatientAO.getPatientCardNo());
        PatInfoRes patInfoRes = wsRequestService.patInfoQuery(patInfoQueryDTO);
        Patient patient = patInfoRes == null ? null : patientService.findByHisId(patInfoRes.getAccessPatId());
        PatInfoResVO patInfoResVO=new PatInfoResVO();
        BeanUtils.copyProperties(patInfoRes,patInfoResVO);
        patInfoResVO.setPatientId(patient==null?null:patient.getId());
        patInfoResVO.setPatCardno(patient == null ? null : patient.getPatientCardNo());
        patInfoResVO.setPatCardType(patient == null ? null : patient.getPatientCardType());
        return ResultBuilder.success(patInfoResVO);
    }


    @ApiOperation("预约")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.ADD, desc = "预约")
    @PostMapping("/confirm")
    public ResultDTO<Long> confirm(@RequestBody DoctorScheduleConfirmAO doctorScheduleConfirmAO) throws BizException {
        Doctor doctor = doctorService.findById(ReqComTool.getUserId());
        CommonTool.checkObj(doctor, "10160001");
        Patient patient = patientService.findById(doctorScheduleConfirmAO.getPatientId());
        CommonTool.checkObj(patient, "10160002");
        OrderRegisterDTO orderRegisterDTO = DoctorScheduleTool.buildWsDTO(doctorScheduleConfirmAO, patient.getHisPatientId());
        OrderRegisterRes registerRes = null;
        try{
            registerRes = wsRequestService.orderReg(orderRegisterDTO);
        }catch (Exception e){
            return ResultBuilder.failure("10160001", "预约失败，请重新操作！");
        }
        OrderReg orderReg = DoctorScheduleTool.buildWsDTO2Model(registerRes, doctor, patient);
        orderReg.setHosName(appName);
        // 处理其他数据
        orderReg.setPatPhone(patient.getPhone());
        orderReg.setPatCardNo(patient.getPatientCardNo());
        // 查询排班信息
        DoctorSchedule doctorSchedule = doctorScheduleService.queryByAccessSchId(doctorScheduleConfirmAO.getHisSchId());
        if(doctorSchedule != null){
            orderReg.setDeptName(doctorSchedule.getDeptName());
            orderReg.setSchDate(doctorSchedule.getSchDate());
            orderReg.setRegFee(doctorSchedule.getRegFee());
            orderReg.setCost(doctorSchedule.getCost());
            orderReg.setServiceFee(doctorSchedule.getServiceFee());
            orderReg.setDayType(Integer.parseInt(doctorSchedule.getDayType()));
        }
        orderRegService.insert(orderReg);
        return ResultBuilder.success(orderReg.getId());
    }
}
